<?php
	defined('_JEXEC') or die('Restricted access');
	
    
    class t_strings_utility_namespace
	{
        // property declaration
        // public
        const separator_level_0 = '@';
		const separator_level_1 = '|';
        const separator_level_2 = ',';
        // method declaration
		// public
        public function __construct() 
		{
        }
        
        // C
		public function check_string_parameters($a_obj,$a_name,
			$a_separator_char,$a_string_parameters, $a_last_position_parameter,
			$a_error_label,$a_ignore_overcoming_limits = false)
		{
			//echo "a_string_parameters: $a_string_parameters <BR>"; 
			$local_array = explode($a_separator_char,
                $a_string_parameters);
              
            unset($local_array[count($local_array)-1]);       
            unset($local_array[0]);  
            reset($local_array);
            //echo "local_array[1]: ".$local_array[1]."<BR>";    
            //echo "required_actions_string(".count($local_array)."): $required_actions_string <BR>";    
            if ($a_ignore_overcoming_limits)
            {
               /* if ((count($local_array)) < ($a_last_position_parameter-1))    
                    throw new Exception('Error creating object class '.get_class($a_obj).
                        " named: \"$a_name\". Not enough required $a_error_label were specified(".
                        (count($local_array)) . ' instead of '.
                        ($a_last_position_parameter-1).').');	*/
            }
            else
            {
                if ((count($local_array)) > ($a_last_position_parameter-1))    
                    throw new Exception('Error creating object class '.get_class($a_obj).
                        " named: \"$a_name\". Wrong required $a_error_label number were specified(".
                        (count($local_array)) . ' instead of '.
                        ($a_last_position_parameter-1).').');	
            }
			return $local_array;
		}
		public function check_json_string_parameters($a_obj,$a_name,
			$a_separator_char,$a_string_parameters, $a_last_position_parameter,
			$a_error_label,$a_ignore_overcoming_limits = false)
		{
			//echo "a_string_parameters: $a_string_parameters <BR>";
			
			if (is_array($a_string_parameters))
				$local_array = $a_string_parameters;
			else	
				$local_array = json_decode(str_replace('\\', '\\\\',$a_string_parameters));
				
			
              
           // unset($local_array[count($local_array)-1]);       
            //unset($local_array[0]);  
            //reset($local_array);
           // var_dump($local_array);    
            //echo "<BR>";
			//echo "required_actions_string(".count($local_array)."): $required_actions_string <BR>";    
            if (($local_array == NULL) && (($a_string_parameters != '[]') && (!is_array($a_string_parameters))) ) 
			{
				if(PHP_VERSION_ID >= 50300)
				{
					throw new Exception('Error creating object class '.get_class($a_obj).
						" named: \"$a_name\". Error json deconding: " . json_last_error(). 
						"for input string \"$a_error_label\": $a_string_parameters");	
					
				}
				else
				{
					throw new Exception('Error creating object class '.get_class($a_obj).
						" named: \"$a_name\". Bad json deconding ". 
						"for input string \"$a_error_label\": $a_string_parameters");	
					//print_r($a_string_parameters);	
				}
			}
			else if ($a_ignore_overcoming_limits)
            {
               /* if ((count($local_array)) < ($a_last_position_parameter-1))    
                    throw new Exception('Error creating object class '.get_class($a_obj).
                        " named: \"$a_name\". Not enough required $a_error_label were specified(".
                        (count($local_array)) . ' instead of '.
                        ($a_last_position_parameter-1).').');	*/
            }
            else
            {
                if ((count($local_array)) != ($a_last_position_parameter))    
                    throw new Exception('Error creating object class '.get_class($a_obj).
                        " named: \"$a_name\". Wrong required $a_error_label number were specified(".
                        (count($local_array)) . ' instead of '.
                        ($a_last_position_parameter).').');	
            }
			return $local_array;
		}
		
		// E
		public function explode($a_separator_char,$a_string_parameters)
		{
			$local_array = explode($a_separator_char,
                $a_string_parameters);
              
            unset($local_array[count($local_array)-1]);       
            unset($local_array[0]);  
            reset($local_array);
			return $local_array;
		}		
        public function extract_from_position($a_str,$a_separator,$a_position)
        {   
        
            $local_array = explode($a_separator,$a_str);
            //echo "$a_str - $a_separator - $a_position - $local_array[$a_position] ---- ";
            return $local_array[$a_position];
        }
		
        // G
        public function get_ambient_datetime_fromat_from_mysql_date_value($a_value)
        {  
            global $g_ambient_namespace;
			//$l_phpdate = new DateTime($a_value);
			//return $l_phpdate->format($g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format);
			//echo "a_value: $a_value<br>";
            $l_phpdate = strtotime( $a_value );
			//echo "l_phpdate: $l_phpdate<br>";
			if ($a_value == '') 
				return '';
			else
				return date( $g_ambient_namespace->php_date_format, $l_phpdate );
        }		
        public function get_ambient_datetime_fromat_from_mysql_datetime_value($a_value)
        {  
            global $g_ambient_namespace;
			//$l_phpdate = new DateTime($a_value);
			//return $l_phpdate->format($g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format);
            $l_phpdate = strtotime( $a_value );
			//echo "l_phpdate: $l_phpdate<br>";
			if ($l_phpdate == -62169962400) /*-62169962400 corrispond to 0000-00-00 00:00:00 mysql value*/
				return '';
			else
				return date( $g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format, $l_phpdate );
        }
        public function get_ambient_datetime_fromat_from_mysql_time_value($a_value)
        {  
            global $g_ambient_namespace;
			//$l_phpdate = new DateTime($a_value);
			//return $l_phpdate->format($g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format);
            $l_phpdate = strtotime( $a_value );
			//echo "l_phpdate: $l_phpdate<br>";
			if ($l_phpdate == -62169962400) /*-62169962400 corrispond to 0000-00-00 00:00:00 mysql value*/
				return '';
			else
				return date( $g_ambient_namespace->php_time_format, $l_phpdate );
        }
		
		public function get_disguised_value($a_value)
        {
			global $g_ambient_namespace;
			global $g_url_parameters_namespace;
			global $g_cuteengine;
			
			if (SITE_FOLDER != '')
				$local_site_folder = SITE_FOLDER.'\\\\';
			$local_from = array(
				"__CE_SITE_FOLDER__", 
				"__CE_CURRENT_URL__", 
				"__CE_CURRENT_URL_DEPTH_1__", // to delete
				"__CE_CURRENT_URL_DEPTH_2__", // to delete
				"__CE_PARENT_PAGE_URL__",
				"__CE_USER_ID__",
				"__CE_HTTP_USER_AGENT__",
				"__CE_DEPTH_1_", /* DEPTH tags must be the last to be replaced */
				"__CE_DEPTH_2_");
			$local_to = array(
				$local_site_folder, 
				$g_ambient_namespace->get_absolute_web_file_path(false).$g_url_parameters_namespace->compute_disguised_parameters_string(),
				"__CE_CURRENT_URL__",
				"__CE_CURRENT_URL_DEPTH_1__", 
				$g_cuteengine->parent_page_url,
				$g_cuteengine->user->id,
				$_SERVER["HTTP_USER_AGENT"],
				"__CE_", 
				"__CE_DEPTH_1_");
		
			return str_replace($local_from,$local_to,$a_value);
		}
		
		public function get_disguised_separator($a_value)
        {
			global $g_ambient_namespace;
			global $g_url_parameters_namespace;
			global $g_cuteengine;
			
			if (SITE_FOLDER != '')
				$local_site_folder = SITE_FOLDER.'\\\\';
			$local_from = array(			
				"__CE_SEPARATOR_LEVEL_0__",
				"__CE_SEPARATOR_LEVEL_1__",
				"__CE_SEMICOLON__");
			$local_to = array(
				t_query_parameter::separator_level_0,
				t_query_parameter::separator_level_1,
				":");
		
			return str_replace($local_from,$local_to,$a_value);
		}
	
		
		function get_money_format($format, $number) 
		{
			if (function_exists(money_format))
				return money_format($format, $number);
			else
				return $this->money_format_implementation($format, $number);
		}
        public function get_mysql_datetime_fromat_from_ambient_datetime_value($a_value)
        {  
            //echo "a_value:$a_value<br>";
			global $g_ambient_namespace;
			//echo 'PHP_VERSION_ID: '.PHP_VERSION_ID.'<br>';
			if(PHP_VERSION_ID < 50300)
			{
				$dMask = array(
					'a'=>'am/pm',
					'H'=>'hour',
                    'g'=>'hour',
					'i'=>'minute',
					's'=>'second',
					'y'=>'year',
                    'Y'=>'year',
					'm'=>'month',
					'd'=>'day'
				);
                $l_array = array(
					'hour'=>'00',
					'minute'=>'00',
					'second'=>'00',
                    'year'=>'0000',
					'month'=>'00',
					'day'=>'00'
                );
                $l_separator = str_replace('/','\/',$g_ambient_namespace->date_separator.$g_ambient_namespace->time_separator);
               // echo "l_separator: $l_separator - pattern: ".$g_ambient_namespace->php_date_format . ' ' .$g_ambient_namespace->php_time_format.'<br>';
				$format = preg_split('/[\s'.$l_separator.']+/', $g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format, -1, PREG_SPLIT_NO_EMPTY);  
                //$format = preg_split('//', $g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format, -1, PREG_SPLIT_NO_EMPTY);  
				//print_r($format);
				$date = preg_split('/[\s'.$l_separator.']+/', $a_value, -1, PREG_SPLIT_NO_EMPTY);  
                //$date = preg_split('//', $a_value, -1, PREG_SPLIT_NO_EMPTY);  
				//print_r($date);
                $l_ampm = false;
				foreach ($date as $k => $v) {
                    //echo "v:$v<br>";
					if ($dMask[$format[$k]])
                    {
                       $l_ampm = $l_ampm || ($dMask[$format[$k]] == 'am/pm');
					   $l_array[$dMask[$format[$k]]] = $v;
                    }    
				}
				//echo "l_array['am/pm']: ".$l_array['am/pm']. "<br>";
				if (($l_ampm) and ($l_array['am/pm'] == 'pm'))
					$l_array['hour'] += 12;
				//echo "l_array['hour']: ".$l_array['hour']. "<br>";	
				
			}	
			else
				$l_array = date_parse_from_format ( $g_ambient_namespace->php_date_format . " " .$g_ambient_namespace->php_time_format , $a_value );
			//echo "l_array:". print_r($l_array) ."fine PRINT<br>";
			$local_result = '';
			if (trim($l_array[year]) != '')
				$local_result = "$l_array[year]-$l_array[month]-$l_array[day] ";
			if (trim($l_array[hour]) != '')
				$local_result = $local_result."$l_array[hour]:$l_array[minute]:$l_array[second]";
			return trim($local_result);
			/*return "$l_array[year]-$l_array[month]-$l_array[day] $l_array[hour]:$l_array[minute]:$l_array[second]";*/
        }        
		public function get_javascript_code_to_hide_separetor($a_index_name,$a_destination_variable_name,$a_source_variable_name)
        {   
            return "if ($a_destination_variable_name == '')  
				$a_destination_variable_name += '".t_url_parameter::separator_level_0."' + hide_separator($a_source_variable_name);
			else    
				$a_destination_variable_name += '".t_url_parameter::separator_level_1."' + hide_separator($a_source_variable_name);
            ";    
        }
		//M
		/* 
		That it is an implementation of the function money_format for the 
		platforms that do not it bear.  

		The function accepts to same string of format accepts for the 
		original function of the PHP.  

		*/ 
		function money_format_implementation($format, $number) 
		{ 
			$regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'. 
					  '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/'; 
			if (setlocale(LC_MONETARY, 0) == 'C') { 
				setlocale(LC_MONETARY, ''); 
			} 
			$locale = localeconv(); 
			preg_match_all($regex, $format, $matches, PREG_SET_ORDER); 
			foreach ($matches as $fmatch) { 
				$value = floatval($number); 
				$flags = array( 
					'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? 
								   $match[1] : ' ', 
					'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0, 
					'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? 
								   $match[0] : '+', 
					'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0, 
					'isleft'    => preg_match('/\-/', $fmatch[1]) > 0 
				); 
				$width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0; 
				$left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0; 
				$right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits']; 
				$conversion = $fmatch[5]; 

				$positive = true; 
				if ($value < 0) { 
					$positive = false; 
					$value  *= -1; 
				} 
				$letter = $positive ? 'p' : 'n'; 

				$prefix = $suffix = $cprefix = $csuffix = $signal = ''; 

				$signal = $positive ? $locale['positive_sign'] : $locale['negative_sign']; 
				switch (true) { 
					case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+': 
						$prefix = $signal; 
						break; 
					case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+': 
						$suffix = $signal; 
						break; 
					case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+': 
						$cprefix = $signal; 
						break; 
					case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+': 
						$csuffix = $signal; 
						break; 
					case $flags['usesignal'] == '(': 
					case $locale["{$letter}_sign_posn"] == 0: 
						$prefix = '('; 
						$suffix = ')'; 
						break; 
				} 
				if (!$flags['nosimbol']) { 
					$currency = $cprefix . 
								($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . 
								$csuffix; 
				} else { 
					$currency = ''; 
				} 
				$space  = $locale["{$letter}_sep_by_space"] ? ' ' : ''; 

				$value = number_format($value, $right, $locale['mon_decimal_point'], 
						 $flags['nogroup'] ? '' : $locale['mon_thousands_sep']); 
				$value = @explode($locale['mon_decimal_point'], $value); 

				$n = strlen($prefix) + strlen($currency) + strlen($value[0]); 
				if ($left > 0 && $left > $n) { 
					$value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0]; 
				} 
				$value = implode($locale['mon_decimal_point'], $value); 
				if ($locale["{$letter}_cs_precedes"]) { 
					$value = $prefix . $currency . $space . $value . $suffix; 
				} else { 
					$value = $prefix . $value . $space . $currency . $suffix; 
				} 
				if ($width > 0) { 
					$value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? 
							 STR_PAD_RIGHT : STR_PAD_LEFT); 
				} 

				$format = str_replace($fmatch[0], $value, $format); 
			} 
			return $format; 
		} 
    }
    
    global $g_strings_utility_namespace;
    $g_strings_utility_namespace = new t_strings_utility_namespace;
?>    